/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the koala4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @Author: GuoYang
 */

package com.koalacloud.koala.zhaikucloud.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.koalacloud.koala.common.core.util.R;
import com.koalacloud.koala.common.log.annotation.SysLog;
import com.koalacloud.koala.common.security.annotation.Inner;
import com.koalacloud.koala.zhaikucloud.dto.MallProductDTO;
import com.koalacloud.koala.zhaikucloud.entity.MallProduct;
import com.koalacloud.koala.zhaikucloud.util.EsDataOperation;
import com.koalacloud.koala.zhaikucloud.util.EsIndexOperation;
import com.koalacloud.koala.zhaikucloud.util.EsQueryOperation;
import com.koalacloud.koala.zhaikucloud.service.MallProductService;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 商品表
 *
 * @Author: GuoYang
 * @date 2022-01-28 10:38:36
 */
@RestController
@RequiredArgsConstructor
//@Inner(value = false)
@RequestMapping("/mallProduct" )
@Tag(description = "mallProduct" , name = "商品表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class MallProductController {

    private final MallProductService mallProductService;

    private final EsDataOperation esDataOperation;

    private final EsIndexOperation esIndexOperation;

    private final EsQueryOperation esQueryOperation;

    /**
     * 分页查询
     * @param page 分页对象
     * @param mallProduct 商品表
     * @return
     */
    @Inner(value = false)
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('mallProduct_view')" )
    public R getMallProductPage(Page page, MallProduct mallProduct) {
        return R.ok(mallProductService.page(page, Wrappers.query(mallProduct)));
    }

    /**
     * 通过id查询商品表
     * @param id id
     * @return R
     */
    @Inner(value = false)
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
//    @PreAuthorize("@pms.hasPermission('mallProduct_view')" )
    public R getById(@PathVariable("id" ) String id) {
        return R.ok(mallProductService.getById(id));
    }

    /**
     * 新增商品表
     * @param mallProduct 商品表
     * @return R
     */
    @Operation(summary = "新增商品表", description = "新增商品表")
    @SysLog("新增商品表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('mallProduct_add')")
    public R save(@RequestBody MallProduct mallProduct) {
        return R.ok(mallProductService.save(mallProduct));
    }

    /**
     * 修改商品表
     * @param mallProduct 商品表
     * @return R
     */
    @Operation(summary = "修改商品表", description = "修改商品表")
    @SysLog("修改商品表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('mallProduct_edit')")
    public R updateById(@RequestBody MallProduct mallProduct) {
        return R.ok(mallProductService.updateById(mallProduct));
    }

    /**
     * 通过id删除商品表
     * @param ids id 列表
     * @return R
     */
    @Operation(summary = "通过id删除商品表", description = "通过id删除商品表")
    @SysLog("通过id删除商品表")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('mallProduct_del')")
    public R removeById(@RequestBody String[] ids) {
        return R.ok(mallProductService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 通过id查询用户电话号码
     * @param id id
     * @return R
     */
    @Inner(value = false)
    @Operation(summary = "通过id查询用户电话号码", description = "通过id查询用户电话号码")
    @SysLog("通过id查询用户电话号码")
    @GetMapping("/phone/{id}")
    public R getPhoneById(@PathVariable String id) {
        return R.ok(mallProductService.getUserPhone(id));
    }

    /**
     * FromSize分页查询
     * @param page 分页查询Document
     * @return
     */
    @Inner(value = false)
    @Operation(summary = "分页查询Document", description = "分页查询Document")
    @GetMapping("/doc/fromSize")
    public R getMallProductFromSize(Page page) throws IOException {
        List<MallProductDTO> list = esQueryOperation.fromSize(MallProductDTO.class, (int)page.getCurrent(), (int)page.getSize());
        return R.ok(list);
    }

    /**
     * 分页查询Es searchAfter分页
     * @param sortValue 排序后的值
     * @param size 显示条数
     * @param mallProduct 商品表
     * @return
     */
    @Inner(value = false)
    @Operation(summary = "searchAfter分页", description = "searchAfter分页")
    @GetMapping("/doc/searchAfter/{sortValue}/{size}")
    public R getMallProductPageEs(@PathVariable String sortValue, @PathVariable Integer size, MallProductDTO mallProduct) {
        Map<String, Object> map = new HashMap<>();
        List<MallProductDTO> list = null;
        // 第一次sortId无值，按照时间排序。以便获取sortId，第二次作为分页条件。
//        if (StrUtil.isEmpty(sortId)) {
        if (sortValue.equals("0")) {
            list = esQueryOperation.OrderQuery(MallProductDTO.class, "updateTime", size);
        } else {
            list = esQueryOperation.searchAfter(MallProductDTO.class, "updateTime", sortValue, size);
        }

        if (list.size() > 0) {
            MallProductDTO mallProductDTO = list.get(list.size() - 1);
//            map.put("id", mallProductDTO.getId());
            map.put("id", mallProductDTO.getUpdateTime().getTime());
            map.put("createTime", mallProductDTO.getUpdateTime());
        }

        map.put("result", list);
        return R.ok(map);
    }

    /**
     * 通过id查询商品表Es
     * @param id id
     * @return R
     */
    @Inner(value = false)
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/doc/{id}")
    public R getByIdEs(@PathVariable("id" ) String id) {
        MallProductDTO mallProduct = esDataOperation.getById(id, MallProductDTO.class);
        return R.ok(mallProduct);
    }

    @Inner(value = false)
    @Operation(summary = "多字段匹配", description = "多字段匹配")
    @GetMapping("/doc/multiMatch/{key}")
    public R multiMatch(@PathVariable String key) {
        return R.ok(esQueryOperation.multiMatch(MallProductDTO.class, key, "title", "sellPoint", "creditor_address"));
    }

    /**
     * 导出excel 表格
     * @param mallProduct 查询条件
     * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('mallProduct_export')" )
    public List<MallProduct> export(MallProduct mallProduct,String[] ids) {
        return mallProductService.list(Wrappers.lambdaQuery(mallProduct).in(ArrayUtil.isNotEmpty(ids), MallProduct::getId, ids));
    }
}
